package com.iking.toolkit.thread;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 功能描述：线程池
 *
 * @author: xuesen
 * @date: 2022/12/20 15:07
 */
@Configuration
public class FileFormatThreadPoolConfig {

    /**
     * 收集线程池
     *
     * @return
     */
    @Bean
    public Executor fileFormatThreadPool() {
        return createFixTaskExecutor(5, "fileFoamat-thread-", 2000);
    }

    /**
     * 创建固定核心线程池
     *
     * @param theadCount
     * @param treadName
     * @return
     */
    private ThreadPoolTaskExecutor createFixTaskExecutor(int theadCount, String treadName, int queueSize) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(theadCount);
        //设置最大线程数
        executor.setMaxPoolSize(theadCount);
        //设置队列容量
        executor.setQueueCapacity(queueSize);
        //设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(0);
        //设置默认线程名称
        executor.setThreadNamePrefix(treadName);
        //设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //等待时长
        executor.setAwaitTerminationSeconds(10);
        executor.initialize();
        return executor;
    }

}
